<?php

class ShopController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/simple';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
//			'deleteOwn + delete', // we only allow deletion via POST request
//            'updateOwn + update', // Apply this filter only for the update action.
//            'rights',
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
//			array('allow',  // allow all users to perform 'index' and 'view' actions
//				'actions'=>array('index','view','create','update','admin','delete'),
//				'users'=>array('admin'),
//			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','view','index','api','admin'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','view','create','update','admin','delete','api'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
        $m = $this->loadModel($id);
        if(isset($_POST["enabled"])){
            $m->enabled = intval($_POST["enabled"]);
            $m->save();
        }

		$this->render('view',array(
			'model'=>$m,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($data=NULL)
	{
		$model=new Shop;


		//api传递参数
		if (!empty($data)){
			$_POST['Shop']['title'] = $data->title;
			$_POST['Shop']['type'] = $data->type;
			$_POST['Shop']['longitude'] = $data->longitude;
			$_POST['Shop']['latitude'] = $data->latitude;
		}
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Shop']))
		{   
			$user_id = Yii::app()->user->id;
			$model->attributes=$_POST['Shop'];
			
            $img_root = Yii::app()->getBasePath().DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
            $model->cid=0;
//            $model->type=0;
            $model->order=0;
            $model->enabled=1;

            $model->uid = $user_id;
            $time =time();
            $model->ctime = $time;
            $model->utime = $time;

            $img = CUploadedFile::getInstance($model, 'img');
            if(!empty($img)){
                if(!is_dir($img_root.$user_id.DIRECTORY_SEPARATOR)){
                    mkdir($img_root.$user_id.DIRECTORY_SEPARATOR,0777,true);
                }
                $img_name  = md5(rand(1,100).date('YmdHis').rand(1,1000)).'.'.$img->extensionName;
                if (is_object($img)) {
                    $img->saveAs($img_root.$user_id.DIRECTORY_SEPARATOR.$img_name);
                    $model->img='/images/temp/'.$user_id.'/'.$img_name;
                }
            }else{
                $model->img='';
            }

			if($model->save())
				if ($data){
					return true;
				}else{
					$this->redirect(array('view','id'=>$model->aid));
				}
//            if($model->save()){
//                pd(json_encode(array('right'=>$model->attributes)));
//            }else{
//                pd(json_encode(array('error'=>$model->errors)));
//            }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

    public function filterUpdateOwn($filterChain)
    {
        $id = Yii::app()->request->getParam('id', 0);
        $imgs=$this->loadModel($id);

        // Remove the 'rights' filter if the user is updating an own post
        // and has the permission to do so.
        if(Yii::app()->user->checkAccess('ImgsUpdateOwn', array('userid'=>$imgs->uid)))
            $filterChain->removeAt(1);

        $filterChain->run();
    }

    public function filterDeleteOwn($filterChain)
    {
        $id = Yii::app()->request->getParam('id', 0);
        $imgs=$this->loadModel($id);

        // Remove the 'rights' filter if the user is updating an own post
        // and has the permission to do so.
        if(Yii::app()->user->checkAccess('ImgsDeleteOwn', array('userid'=>$imgs->uid)))
            $filterChain->removeAt(1);

        $filterChain->run();
    }

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id,$data=NULL)
	{
		$model=$this->loadModel($id);

		//api传递参数
		if (!empty($data)){
			$_POST['Shop']['type'] = $data->type;
			$_POST['Shop']['longitude'] = $data->longitude;
			$_POST['Shop']['latitude'] = $data->latitude;
		}
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Shop']))
		{
            $user_id = Yii::app()->user->id;
            $model->attributes=$_POST['Shop'];

            $img_root = Yii::app()->getBasePath().DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
            $model->cid=0;
//            $model->type=0;
            $model->order=0;
            $model->enabled=1;

            $model->uid = $user_id;
            $time =time();
            $model->ctime = $time;
            $model->utime = $time;

            $img = CUploadedFile::getInstance($model, 'img');
            if(!empty($img)){
                if(!is_dir($img_root.$user_id.DIRECTORY_SEPARATOR)){
                    mkdir($img_root.$user_id.DIRECTORY_SEPARATOR,0777,true);
                }
                $img_name  = md5(rand(1,100).date('YmdHis').rand(1,1000)).'.'.$img->extensionName;
                if (is_object($img)) {
                    $img->saveAs($img_root.$user_id.DIRECTORY_SEPARATOR.$img_name);
                    $model->img='/images/temp/'.$user_id.'/'.$img_name;
                }
            }else{
                $model->img='';
            }

            if($model->save()){
            	if ($data){
            		return true;
            	}else {
                	$this->redirect(array('view','id'=>$model->aid));
            	}
            }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Imgs');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Shop('search');
		$model->unsetAttributes();  // clear any default values
//        $model->uid = Yii::app()->user->id;
		if(isset($_GET['Shop']))
			$model->attributes=$_GET['Shop'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Imgs the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Shop::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Imgs $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='imgs-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionApi()
	{
		//$data = '{"title":"sdsds\u6d4b\u8bd5\u6dfb\u52a0","type":"1","longitude":"118.26746232","latitude":"32.09306833"}';
		$data = json_decode($_GET['data']);
		
		if ($data->title){
			$db = new CDbCriteria;
			$db->select = 'aid';
			$db->condition='title=:title';  
			$db->params=array(':title'=>$data->title);  
			$shop = Shop::model()->find($db);
			
			if (empty($shop->aid)){
				self::actionCreate($data);
			}else{
				self::actionUpdate($shop->aid,$data);
			}
		}
		
		Yii::app()->end();
	}
}
